/*
 * 作者: junmu
 * 时间: 2025-07-22
 */
package com.hzbc.faceattendance.controller;

import com.hzbc.faceattendance.dto.ApiResponse;
import com.hzbc.faceattendance.dto.PasswordChangeRequest;
import com.hzbc.faceattendance.dto.RefreshTokenRequest;
import com.hzbc.faceattendance.model.AdminUser;
import com.hzbc.faceattendance.security.JwtRequest;
import com.hzbc.faceattendance.service.IAuthService;
import com.hzbc.faceattendance.utils.JwtUtil;
import io.jsonwebtoken.ExpiredJwtException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Tag(name = "认证管理", description = "用户认证相关接口")
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private static final long EXPIRATIONMS = 3 * 60 * 60 * 1000;
    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private IAuthService authService;

    @Autowired
    private UserDetailsService userDetailsService;


    @Operation(summary = "修改密码")
    @PostMapping("/changePassword")
    public ApiResponse<?> changePassword(@RequestBody PasswordChangeRequest request) {
        return authService.changePassword(request);
    }

    @Operation(summary = "刷新token", description = "使用用户名密码获取JWT令牌")
    @PostMapping("/refresh-token")
    public ApiResponse<?> refreshToken(@RequestBody RefreshTokenRequest request) {
        try {
            String username;
            try {
                // 捕获所有JWT解析异常
                username = jwtUtil.extractUsername(request.getRefreshToken());
            } catch (ExpiredJwtException e) {
                return new ApiResponse<>(false, 401, "无效的刷新token", null);
            }

            try {
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);

                // 先验证token有效性（包含时钟偏移校验）
                if (!jwtUtil.validateToken(request.getRefreshToken(), userDetails)) {
                    return new ApiResponse<>(false, 401, "token验证失败", null);
                }

                // 直接生成新token（移除缓存检查逻辑）
                String newAccessToken = jwtUtil.generateToken(userDetails);
                String refreshToken = jwtUtil.generateRefreshToken(userDetails, EXPIRATIONMS);

                Map<String, String> response = new HashMap<>();
                response.put("token", newAccessToken);
                response.put("refreshToken", refreshToken);
                return new ApiResponse<>(true, 0, "Token刷新成功", response);

            } catch (UsernameNotFoundException e) {
                return new ApiResponse<>(false, 401, "用户不存在", null);
            }
        } catch (Exception e) {
            // 统一返回401并记录日志
            log.error("Token刷新异常", e);
            return new ApiResponse<>(false, 401, "token刷新失败：" + e.getMessage(), null);
        }
    }

    @PostMapping("/login")
    public ApiResponse<?> login(@RequestBody JwtRequest request) throws Exception {
        ResponseEntity<?> response = authService.createAuthenticationToken(request);
        int value = response.getStatusCode().value();
        String stringBody = response.getBody().toString();
        if (401 == value) {
            if ("用户不存在".equals(stringBody)) {
                return new ApiResponse<Object>(false, 401, "用户不存在", response.getBody());
            }
            return new ApiResponse<Object>(false, 401, "用户名或密码错误", response.getBody());
        }
        return new ApiResponse<Object>(true, 0, "登录成功", response.getBody());
    }

    @Operation(summary = "用户注册", description = "创建新用户账号")
    @PostMapping("/register")
    public ApiResponse<?> registerUser(@RequestBody AdminUser adminUser) {
        try {
            // 检查用户是否已经存在
            userDetailsService.loadUserByUsername(adminUser.getUsername());
            return new ApiResponse<>(false, 409, "该用户已存在", null);
        } catch (UsernameNotFoundException e) {
            // 用户不存在，继续注册流程
            ResponseEntity<?> response = authService.registerUser(adminUser);
            return new ApiResponse<>(true, 0, "注册成功", response.getBody());
        } catch (Exception e) {
            // 其他异常情况
            log.error("注册异常", e);
            return new ApiResponse<>(false, 500, "注册失败：" + e.getMessage(), null);
        }
    }


}
